package com.atguigu.gmall.component;

import com.atguigu.gmall.common.consts.RedisConst;
import com.atguigu.gmall.common.execption.GmallException;
import com.atguigu.gmall.common.result.ResultCodeEnum;
import com.atguigu.gmall.common.util.JsonUtil;
import com.atguigu.gmall.model.cart.entity.CartInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import java.time.Duration;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author:lyd
 **/
@Repository
public class CartRepository {
    @Autowired
    StringRedisTemplate redisTemplate;

    /**
     * 判断购物车中是否有该商品
     *
     * @param cartKey
     * @param skuId
     * @return
     */
    public Boolean hasKey(String cartKey, String skuId) {
        HashOperations<String, String, String> hash = redisTemplate.opsForHash();
        return hash.hasKey(cartKey, skuId);
    }


    /**
     * 根据key获取购物车信息
     *
     * @param cartKey
     * @param skuId
     * @return
     */
    public CartInfo getCart(String cartKey, String skuId) {
        HashOperations<String, String, String> hash = redisTemplate.opsForHash();
        String cartInfoJson = hash.get(cartKey, skuId);
        if (StringUtils.hasText(cartInfoJson)) {
            return JsonUtil.strToObj(cartInfoJson, CartInfo.class);
        }
        return null;
    }

    /**
     * 保存购物车信息
     *
     * @param cartKey
     * @param skuId
     * @param cart
     */
    public void saveCart(String cartKey, String skuId, CartInfo cart) {
        HashOperations<String, String, String> hash = redisTemplate.opsForHash();
        //限制购物车每件商品数量
        if (cart.getSkuNum()> RedisConst.CART_ITEM_SIZE_LIMIT) {
            throw new GmallException(ResultCodeEnum.CART_ITEM_SIZE_LIMIT);
        }
        hash.put(cartKey, skuId, JsonUtil.objToJsonStr(cart));
    }

    /**
     * 获取购物车列表
     *
     * @return
     */
    public List<CartInfo> cartList(String cartKey) {
        HashOperations<String, String, String> hash = redisTemplate.opsForHash();
        List<CartInfo> cartInfos = hash.values(cartKey)
                .stream()
                .map(item -> JsonUtil.strToObj(item, CartInfo.class))
                .sorted((o1, o2) -> o2.getCreateTime().compareTo(o1.getCreateTime()))
                .collect(Collectors.toList());
        return cartInfos;
    }

    public void remove(String cartKey, String skuId) {
        HashOperations<String, String, String> hash = redisTemplate.opsForHash();
        hash.delete(cartKey, skuId);
    }

    public void deleteChecked(String cartKey) {
        HashOperations<String, String, String> hash = redisTemplate.opsForHash();
        String[] skuIds = hash.values(cartKey)
                .stream()
                .map(item -> JsonUtil.strToObj(item, CartInfo.class))
                .filter(cartInfo -> cartInfo.getIsChecked() == 1)
                .map(CartInfo::getSkuId)
                .map(Object::toString)
                .toArray(String[]::new);//显示指定数组类型
        //避免空删
        if (skuIds.length > 0) {
            hash.delete(cartKey, skuIds);
        }
    }

    public void setCartTtl(String cartKey, Duration duration) {
        redisTemplate.expire(cartKey, duration);
    }

    public Long getCartSize(String cartKey) {
        return redisTemplate.opsForHash().size(cartKey);
    }

    public void deleteItem(String cartKey, String skuId) {
        redisTemplate.opsForHash().delete(cartKey, skuId);
    }
}
